Read, With the Name of Your Lord Who Created

Javascript: Adding OnMouseOver And OnMouseOut Using DOM

Posted by triaslama on February 2, 2008

The DOM (Document Object Model) is a standard way to access a document within a browser. The DOM could be Core DOM, HTML DOM, XML DOM. The DOM can be very handy and useful when we need to access the specific elements of the document and add some effects to them.

The two of the most useful of the DOM methods could be getElementById and getElementsByTagName. The getElementById will return an element that specified as a parameter in getElementById DOM method. The parameter that passed is a string that represents the ID of an element. The getElementsByTagName -that receive one parameter, the element name as string- will return array that represents elements in the document with the tag name specified as a parameter in getElementsByTagName method.

Here a simple example utilization of getElementById and getElementsByTagName method to add an effect -change the background color- when the mouse cursor over a <li> element and reset the background color when then mouse cursor out a <li> element:

SimpleDom.htm

<html>
<head>
<title>Test Something</title>
<script lang=”javascript” type=”text/javascript”>
window.onload = function()
{
var lis = document.getElementsByTagName(“li”);

for (var i=0;i<lis.length;i++) {
lis[i].onmouseover = function()
{
this.style.backgroundColor = “gainsboro”;
};
lis[i].onmouseout = function()
{
this.style.backgroundColor = “white”;
};
}
};
</script>
</head>
<body>
<ul>
<li>First Element</li>
<li>Second Element</li>
<li>Third Element</li>
</ul>
</body>
</html>

Let’s look at the code in more details. The body of the document consist of an unordered list (ul). The <ul> element have three list item <li> element as childs. The scenario is simple change the background color of <li> element when the mouse is moved over around them and reset the background color of <li> element when the mouse is moved out of them.

To attain this functionalities we using Javascript and DOM to access the document specified in the <body> element. The first line of our Javascript code is window.onload, this function is executed when the window object is fully loaded, in the other word the window.onload executed only when the elements inside a document has been rendered.

To handle window.onload we create an inline function that tells what must be done when the page has been loaded. In this case we will retrieve all of <li> element in a document using getElementsByTagName DOM method and save this element in a variable named lis.

var lis = document.getElementsByTagName(“li”);.

The next step iterate through all of <li> element inside lis variable:

for (var i=0;i<lis.length;i++).

But the most important part here we install two events for each of <li> element, onmouseover (happens when the mouse cursor over an <li> element) and onmouseout (happens when the mouse cursor out from an <li> element).

To handle the onmouseover event we create an inline function that changes the background color of <li> element when the mouse cursor over it.

lis[i].onmouseover = function()
{
this.style.backgroundColor = “gainsboro”;
};

To handle event when the mouse cursor out of an <li> element we create an inline function that reset the background color back to its original color.

lis[i].onmouseout = function()
{
this.style.backgroundColor = “white”;
};

The word this above refers to the <li> element that being iterated. When everything is ready and we move the cursor over an <li> element we should see that the background color of <li> that is being hovered change to gainsboro, and the background color will back to white when the mouse cursor leaves the specified <li> element.

The Javascript and DOM can have more functionalities and usages I hope this simple article will give me and all the readers a clue about the advantage of DOM.

27 Responses to “Javascript: Adding OnMouseOver And OnMouseOut Using DOM”

  1. Rhett P said

    Dude, I’ve been wrestling with this exact issue all day. I copied your code and tried to make it work. I changed the color names. Nothing. Didn’t work. I cannot figure out what I am doing wrong. It all looks correct, but nothing happens.

  2. triaslama said

    Hello and thanks for your comment.
    I am sorry for my delays answering your comment. Your problem maybe caused by quotation marks (“) when you copy & paste code from my blog. Try to remove quotation marks and replace it manually. I hope this help, thanks.

  3. Anil said

    Hi Triaslama, I liked your above post but I have a question. I have a DropDownListBox with 4 items in it e.g. Item1, Item2, Item3 and Item4. I want, when I hover my mouse on item1 in the dropdownlistbox I want to display Image1, if I hover my mouse on Item2 I want to diplay image2 and so on…. Can you help me in achieving this .
    I tried your above logic for achieving this but I failed, could give me some idea how to achieve this.
    Thanks in Advance for help.

  4. Carlos said

    You can find a solution by clicking this

  5. cbgraph said

    Thank you for onmouseout = function() {…}!

  6. I loved the post , I will come back absolutely! Mistress rules!

  7. manish nautiyal said

    document.getElementById(id).onmouseover = function(){
    this.style.backgroundColor = “#FF5800”;
    }

    document.getElementById(id).onmouseout = function(){
    this.style.backgroundColor = “#e3e4e6”;
    }

  8. Dominant girls like this one are just the best stress relief ever! More to come?

  9. Thank you so much for this. I was constantly trying

    lis[i].onmouseover = function() { lis[i].style.backgroundColor = “gainsboro”; };

    and it never worked. So the magic word was “this” đŸ™‚

  10. hannah said

    Hi,

    thx for the post.

    I was looking all the time for a solution how to add a “onmouseover” function dynamically with JS (Of course, by logical thinking I tried first “document.getElementById(‘…’).onmouseover=’…’).

    It didn´t work.

    But with your solution it does. đŸ˜€ yaihhh

  11. EFT for stress relief…

    […]Javascript: Adding OnMouseOver And OnMouseOut Using DOM « Read, With the Name of Your Lord Who Created[…]…

  12. arjun said

    thanks for ur help, i m very glad that your code help me Jakarta Banjir Lagi ,

  13. narendra said

    thanks for ur help, i m very glad that your code help me narendra,

  14. jai said

    waste

  15. Thank you very much for the code!

    Please replace “li” as ‘li’ (enclose li in single quote)

  16. comment contd…

    not only around li, but replace double quotes (“) with sinle quote (‘) in the code provided.

  17. Everywhere!

  18. Thanks!

    Worked perfectly after re-typing the ”

    Regards

    Thys

  19. My spouse and I stumbled over here by a different website and thought I should check things out.

    I like what I see so now i am following you.
    Look forward to looking into your web page repeatedly.

  20. Generally I do not read article on blogs, but I wish to say that this write-up very pressured me to try and do it!
    Your writing style has been amazed me. Thank you, quite great
    post.

  21. It’s in point of fact a great and useful piece of info. I am satisfied that you simply shared this useful info with us. Please stay us informed like this. Thanks for sharing.

  22. Tristan said

    Being over thirty is not the end of the fitness road for any
    man. Additionally, because of their shorter length, it becomes easier to perform close-grip
    operations (i. I recommend dumbbells for most people who
    want to maximize their P90X workouts and see the most results.

  23. This is great since I don’t need to grab a pot holder or towel to open the lid. Take this 5 minutes to go ahead and clean up the slow cooker. Make the most of your slow cooker by making clean up a breeze with these simple tips.

  24. I am in fact happy to read this website posts which contains lots of helpful facts, thanks for providing such statistics.

  25. Stephen said

    Today we will be looking at the Oral-B Professional Care Deluxe Electric Toothbrush –
    8850 DLX. The latest Electric Tooth Brushes have options for brush heads and
    they allow different types and shapes of Brush heads to be used as per the
    user’s preferences. Every time my parents will ask me if I brushed my teeth before going to bed I would always say yes even if I didn’t.

  26. Great goods from you, man. I have understand your
    stuff previous to and you are just too great.
    I really like what you have acquired here, certainly like
    what you’re saying and the way in which you say it. You make it entertaining and you still care for to keep it smart. I can not wait to read far more from you. This is actually a tremendous site.

  27. test said

    Marvelous, what a web site it is! This weblog gives useful data to us,
    keep it up.

Leave a comment